package Day025_综合案例;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 * @author zhangyan
 * @date 2020/5/20 10:14
 */
public class Server2 {
    public static void main(String[] args) {
        //接收客户端信息

        //开启服务器时 如果文件不存在就创建
        try {
            File file = new File("Demo02\\stu.txt");
            if (!file.exists()){
                file.createNewFile(); //创建的是空文件
            }
            //如果是一个空文件,使用反序列化流进行反序列化,会报异常
            FileInputStream fis = new FileInputStream("Demo02\\stu.txt");
            ObjectInputStream ois = new ObjectInputStream(fis);
            //释放资源
            ois.close();
        } catch (Exception e) {
            //创建序列化流对象
            try {
                FileOutputStream fos = new FileOutputStream("Demo02\\stu.txt");
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                //创建空集合 写入文件
                ArrayList<Student> list = new ArrayList<>();
                oos.writeObject(list);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        try {
            //创建ServerSocket对象
            ServerSocket ss = new ServerSocket(8888);
            //接收客户端信息
            //由于客户端访问服务器一个功能就连接,操作完毕就断开,需要循环接收连接
            while (true) {
                Socket socket = ss.accept();

                //每个客户端连接,就开启一条线程
                new Thread(()->{
                    try {
                        //获取客户端传过来的数据,得到编号,做出相应的处理
                        InputStream is = socket.getInputStream();
                        byte[] bytes = new byte[1024];
                        int len = is.read(bytes);
                        String message = new String(bytes, 0, len);
                        //获取编号[1] [2]... 在索引1位置
                        char c = message.charAt(1);
                        //根据编号做出相应处理
                        switch (c) {
                            case 1:
                                //添加
                                addStudent(socket,message);
                                break;
                            case 2:
                                //查询
                                selectStudent(socket);
                                break;
                            case 3:
                                //删除
                                deleteStudent(socket,message);
                                break;
                            case 4:
                                //修改
                                setStudent(socket,message);
                                break;
                            case 5:
                                //查询一条数据
                                selectById(socket,message);
                                break;
                        }
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //修改
    private static void setStudent(Socket socket, String message) {
        //获取客户端修改的学生信息
        String s = message.substring(3);
        String[] arr = s.split(",");
        int id = Integer.parseInt(arr[0]);
        String name = arr[1];
        int age = Integer.parseInt(arr[2]);
        String address = arr[3];

        try {
            //反序列化 读取对象
            FileInputStream fis= new FileInputStream("Demo02\\stu.txt");
            ObjectInputStream ois= new ObjectInputStream(fis);
            ArrayList<Student> list = (ArrayList<Student>) ois.readObject();
            //循环遍历集合.找到要修改的对象
            //定义旗帜变量
            boolean flag = false;
            //循环遍历集合,判断id
            for (int i = 0; i < list.size(); i++) {
                //获取学生对象
                Student stu = list.get(i);
                //判断
                if (stu.getID() == id){
                    //修改 输入的是0 就不修改
                    if (!"0".equals(name)){ //name -> arr[1]
                        stu.setName(name);
                    }
                    if (!"0".equals(arr[2])){
                        stu.setAge(age);
                    }
                    if (!"0".equals(arr[3])){
                        stu.setAddress(address);
                    }
                    flag = true;
                    break;
                }
            }

            //修改后集合重写回文件
            FileOutputStream fos = new FileOutputStream("Demo02\\stu.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(list);
            oos.close();
            //服务器返回修改后的信息给客户端
            OutputStream os = socket.getOutputStream();
            if (flag == true){
                os.write("修改成功".getBytes());
            } else {
                os.write("修改失败".getBytes());
            }
            //关闭连接
            ois.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //查询一条数据
    private static void selectById(Socket socket, String message) {
        //获取客户端查询的id
        String s = message.substring(3);
        int id = Integer.parseInt(s);
        //反序列化读取文件中的集合
        try {
            FileInputStream fis = new FileInputStream("Demo02\\stu.txt");
            ObjectInputStream ois = new ObjectInputStream(fis);
            ArrayList<Student> list = (ArrayList<Student>) ois.readObject();
            //定义旗帜变量
            boolean flag = false;
            //循环遍历集合,判断id
            for (int i = 0; i < list.size(); i++) {
                //获取学生对象
                Student stu = list.get(i);
                //判断
                if (stu.getID() == id){

                    flag=true;
                    break;
                }
            }
            //根据判断返回客户端
            OutputStream os = socket.getOutputStream();
            //如果有 返回1
            //如果没有 返回0
            if (flag == true){
                os.write(1);
            } else {
                os.write(0);
            }
            //关流
            ois.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除
    private static void deleteStudent(Socket socket, String message) {
        //获取学员编号 [3]+id
        String s = message.substring(3);
        int id = Integer.parseInt(s);

        //创建反序列化流
        try {
            FileInputStream fis = new FileInputStream("Demo02\\stu.txt");
            ObjectInputStream ois = new ObjectInputStream(fis);
            //读取文件中的集合
            ArrayList<Student> list = (ArrayList<Student>) ois.readObject();

            //判断集合中是否有此id
            boolean flag = false;
            for (int i = 0; i < list.size(); i++) {
                Student stu = list.get(i);
                if(stu.getID() == id){
                    //删除
                    list.remove(i);
                    //修改标记
                    flag = true;
                    //新集合重写回文件
                    //创建序列化流
                    FileOutputStream fos = new FileOutputStream("Demo02\\stu.txt");
                    ObjectOutputStream oos = new ObjectOutputStream(fos);
                    oos.writeObject(list);
                    //结束循环
                    break;
                }
            }

            //服务器回写
            OutputStream os = socket.getOutputStream();
            if (flag == true){
                os.write("删除成功".getBytes());
            } else {
                os.write("删除失败".getBytes());
            }
            //关流
            ois.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查询
    private static void selectStudent(Socket socket) {
        //反序列化文件中的集合对象
        try {
            //创建反序列化流对象
            FileInputStream fis = new FileInputStream("Demo02\\stu.txt");
            ObjectInputStream ois = new ObjectInputStream(fis);
            //反序列化学生对象
            ArrayList<Student> list = (ArrayList<Student>) ois.readObject();
            //服务器回写
            //获取输出流
            OutputStream os = socket.getOutputStream();
            //转换序列化流
            ObjectOutputStream oos = new ObjectOutputStream(os);
            //写出集合
            oos.writeObject(list);
            //关流

            ois.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //添加
    private static void addStudent(Socket socket,String message) {
        //先从文件中 反序列化对象信息

        try {
            //创建反序列化流对象
            FileInputStream fis = new FileInputStream("Demo02\\stu.txt");
            ObjectInputStream ois = new  ObjectInputStream(fis);
            //反序列化学生对象
            ArrayList<Student> list = (ArrayList<Student>)ois.readObject();

            //解析客户端传过来的数据
            String s = message.substring(3);
            String[] arr = s.split(",");
            String name = arr[0];
            int age = Integer.parseInt(arr[1]);
            String address = arr[2];

            //创建学生对象
            //id从1开始自增
            Student stu = new Student(++Utils.id,name,age,address);
            //添加到集合
            list.add(stu);

            //序列化集合到文件中
            //创建序列化流
            FileOutputStream fos = new FileOutputStream("Demo02\\stu.txt");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            //写出到文件
            oos.writeObject(list);

            //服务器回写
            //socket获取输出流
            OutputStream os = socket.getOutputStream();
            //写出数据
            os.write("添加成功".getBytes());
            //关闭资源
            oos.close();
            ois.close();
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
